package org.tea.inventory.admin.web.admin;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.tea.inventory.admin.annotation.LoginAdmin;
import org.tea.inventory.admin.dao.AdminToken;
import org.tea.inventory.admin.service.AdminTokenManager;
import org.tea.inventory.admin.util.bcrypt.BCryptPasswordEncoder;
import org.tea.inventory.base.util.ResponseUtil;
import org.tea.inventory.db.util.ClientIpUtil;
import org.tea.inventory.db.util.JacksonUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.tea.inventory.db.domain.Admin;
import org.tea.inventory.db.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Api("登录")
@RestController
@RequestMapping("/admin/login")
public class AuthController {
    private final Log logger = LogFactory.getLog(AuthController.class);

    @Autowired
    private AdminService adminService;


    /*
     *  { username : value, password : value }
     */
    /**
     * 用户名和密码登录接口
     * @param body 存放用户名和用户密码
     * @return
     */
    @PostMapping("/login")
    public Object login(@RequestBody String body, HttpServletRequest request){
        String username = JacksonUtil.parseString(body, "username");
        //String password = JacksonUtil.parseString(body, "password");

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(JacksonUtil.parseString(body, "password"))){
            return ResponseUtil.badArgument();
        }

        List<Admin> adminList = adminService.findAdmin(username);
        Assert.state(adminList.size() < 2, "同一个用户名存在两个账户");
        if(adminList.size() == 0){
            return ResponseUtil.badArgumentValue();
        }
        Admin admin = adminList.get(0);

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(JacksonUtil.parseString(body, "password"), admin.getPassword())){
            return ResponseUtil.fail(-1, "账号密码不对");
        }

        Integer adminId = admin.getId();
        // token
        AdminToken adminToken = AdminTokenManager.generateToken(adminId);


        Admin adminUser = new Admin();
        adminUser.setId(adminId);
        adminUser.setLastLoginTime( LocalDateTime.now());
        adminUser.setLastLoginIp(ClientIpUtil.getClientIp(request));
        adminService.updateById(adminUser);
        return ResponseUtil.ok(adminToken.getToken());
    }
    /*
     *  { username : value, password : value }
     */
    @PostMapping("/logintest")
    @ApiOperation(value = "登录接口")
    @Cacheable(cacheNames = "user", key = "#root.methodName", unless = "#result == null")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "body", value = "username", paramType = "query", dataType = "String")
    })
    public Object logintest( String username,String password,  HttpServletRequest request){
//        String username = JacksonUtil.parseString(body, "username");
//        //String password = JacksonUtil.parseString(body, "password");

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return ResponseUtil.badArgument();
        }

        List<Admin> adminList = adminService.findAdmin(username);
        Assert.state(adminList.size() < 2, "同一个用户名存在两个账户");
        if(adminList.size() == 0){
            return ResponseUtil.badArgumentValue();
        }
        Admin admin = adminList.get(0);

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(password, admin.getPassword())){
            return ResponseUtil.fail(403, "账号密码不对");
        }

        Integer adminId = admin.getId();
        // token
        AdminToken adminToken = AdminTokenManager.generateToken(adminId);


        Admin adminUser = new Admin();
        adminUser.setId(adminId);
        adminUser.setLastLoginTime( LocalDateTime.now());
        adminUser.setLastLoginIp(ClientIpUtil.getClientIp(request));
        adminService.updateById(adminUser);
        return ResponseUtil.ok(adminToken.getToken());
    }

    /**
     * 退出登录
     * @param adminId 用户Id
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "退出登录接口")
    @ApiImplicitParam(name = "adminId", value = "adminId", paramType = "query", dataType = "String")
    public Object login(@LoginAdmin Integer adminId){
        if(adminId == null){
            return ResponseUtil.unlogin();
        }
        return ResponseUtil.ok();
    }
}
